﻿using System.Net.Http.Headers;
using System.Text;

namespace fCloud.SensorApi.Services;

public interface IHttpService
{
    Task<string> GetAsync(string url);
    Task<string> GetMqttClientsAsync(string url);
}

public class HttpService:IHttpService
{
    private readonly HttpClient _httpClient = new();

    public HttpService(IConfiguration config)
    {
        // _httpClient.DefaultRequestHeaders.Add(
        //     config["Eqmx:ApiKey"]!, config["Eqmx:SecretKey"]);
        // 设置Basic认证头
        var credentials = config["Emqx:ApiKey"]+":"+config["Emqx:SecretKey"];
        var base64Credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Credentials);
        // 添加Content-Type头（虽然GET通常不需要请求体）
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    }

    public async Task<string> GetAsync(string url)
    {
        var response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    public async Task<string> GetMqttClientsAsync(string url)
    {
          var response = await _httpClient.GetAsync(url);
          return await response.Content.ReadAsStringAsync();
    }
}